package com.dreamlike.nlp.Core.Verticle;


import com.dreamlike.nlp.Core.Verticle.Annotation.VerticleComponet;
import com.dreamlike.nlp.Core.CallbackHandler.DeployHandler;
import io.vertx.core.AsyncResult;
import io.vertx.core.Verticle;
import io.vertx.core.Vertx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class VerticleHome {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private Vertx vertx;

    private Map<String, Verticle> verticleIdMap;

    public VerticleHome() {
        this.verticleIdMap = new ConcurrentHashMap<>();
    }

    public void deployVerticle(){
        ArrayList<Verticle> list = new ArrayList<>();
        Collection<Verticle> values = applicationContext.getBeansOfType(Verticle.class).values();
        for (Verticle value : values) {
            int instance = Optional.ofNullable(value.getClass().getAnnotation(VerticleComponet.class))
                    .map(VerticleComponet::instance)
                    .orElse(1);
            for (int i = 0; i < instance; i++) {
                list.add(value);
            }
        }
        list.forEach(v -> vertx.deployVerticle(v,ar -> completionHandler(ar, v)));

    }

    private void completionHandler(AsyncResult<String> asyncResult,Verticle verticle){
        if (verticle instanceof DeployHandler){
            ((DeployHandler) verticle).handle(asyncResult);
        }
        verticleIdMap.put(asyncResult.result(), verticle);
    }

}
